package com.mobi.Survey.map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;

import com.google.android.gms.location.LocationClient;

public class LocationService {

	LocationClient mLocationClient;
	boolean mUpdatesRequested;
	private OnLocationUpdate locationUpdate;

	public static final boolean isNetworkProviderEnabled(final Context ctx) {
		LocationManager lm = null;
		boolean gps_enabled = false, network_enabled = false;
		if (lm == null)
			lm = (LocationManager) ctx
					.getSystemService(Context.LOCATION_SERVICE);
		try {
			gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		} catch (Exception ex) {
		}
		try {
			network_enabled = lm
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		} catch (Exception ex) {
		}

		if (!gps_enabled && !network_enabled) {
			Builder dialog = new AlertDialog.Builder(ctx);
			dialog.setTitle(ctx.getString(R.string.location_service_disabled));
			dialog.setMessage(ctx.getString(R.string.need_access_to_location));
			dialog.setPositiveButton(ctx.getString(R.string.enable),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {
							try {
								Intent myIntent = new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
								ctx.startActivity(myIntent);
							} catch (Exception e) {

							}

						}
					});
			dialog.setNegativeButton(ctx.getString(R.string.cancel),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {

						}
					});
			dialog.show();
			return false;

		} else {
			return true;
		}

	}

	public interface OnLocationUpdate {
		public void onLocationRetrived(Location location);
	}

	public LocationService(OnLocationUpdate locationUpdate) {
		this.locationUpdate = locationUpdate;
	}

	public final void run(Context ctx) {

		final LocationManager locationManager = (LocationManager) ctx
				.getSystemService(Context.LOCATION_SERVICE);
		Location location = locationManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (null == location) {
			location = locationManager
					.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}
		locationUpdate.onLocationRetrived(location);

	}

}
